<template>
  <div class="ai-image-gallery">
    <!-- 头部工具栏 -->
    <div class="gallery-header">
      <div class="header-left">
        <h3 class="gallery-title">
          <svg-icon icon-class="image" style="margin-right: 8px; color: #1EB7E6;" />
          AI生成图片库
        </h3>
        <el-button
          size="mini"
          icon="el-icon-refresh"
          :loading="loading"
          @click="refreshImages"
        >
          刷新
        </el-button>
      </div>

      <div class="header-right">
        <!-- 视图模式切换 -->
        <el-radio-group v-model="viewMode" size="mini" style="margin-right: 15px;">
          <el-radio-button label="grid">网格</el-radio-button>
          <el-radio-button label="list">列表</el-radio-button>
        </el-radio-group>

        <!-- 每页显示数量 -->
        <el-select
          v-model="pageSize"
          size="mini"
          style="width: 100px; margin-right: 10px;"
          @change="handlePageSizeChange"
        >
          <el-option label="12" :value="12" />
          <el-option label="24" :value="24" />
          <el-option label="48" :value="48" />
          <el-option label="96" :value="96" />
        </el-select>

        <!-- 统计信息 -->
        <el-button
          v-if="isAdmin"
          type="info"
          size="mini"
          icon="el-icon-data-line"
          @click="showStatsDialog"
        >
          统计
        </el-button>

        <!-- 删除所有图片 -->
        <el-button
          v-if="isAdmin"
          type="danger"
          size="mini"
          icon="el-icon-delete"
          @click="confirmDeleteAll"
        >
          清空图片
        </el-button>
      </div>
    </div>

    <!-- 图片统计信息 -->
    <div v-if="pagination.total > 0" class="image-stats">
      <el-alert
        :title="`共找到 ${pagination.total} 张AI生成图片`"
        type="info"
        :closable="false"
        show-icon
      />
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" v-loading="loading" class="loading-container">
      <div style="height: 200px;" />
    </div>

    <!-- 空状态 -->
    <div v-else-if="images.length === 0" class="empty-state">
      <div class="empty-content">
        <svg-icon icon-class="image" style="font-size: 48px; color: #C0C4CC; margin-bottom: 16px;" />
        <h3 style="color: #606266; margin-bottom: 8px;">暂无AI生成图片</h3>
        <p style="color: #909399;">您还没有生成过任何AI图片</p>
      </div>
    </div>

    <!-- 图片网格视图 -->
    <div v-else-if="viewMode === 'grid'" class="image-grid">
      <div
        v-for="image in images"
        :key="image.filename"
        class="image-card"
        @click="previewImage(image)"
      >
        <div class="image-wrapper">
          <img
            :src="image.full_url || image.url"
            :alt="image.filename"
            class="gallery-image"
            @error="handleImageError"
            @load="handleImageLoad"
          >

          <!-- 图片遮罩层 -->
          <div class="image-overlay">
            <div class="image-actions">
              <el-button
                type="primary"
                icon="el-icon-view"
                circle
                size="mini"
                @click.stop="previewImage(image)"
              />
              <el-button
                type="success"
                icon="el-icon-download"
                circle
                size="mini"
                @click.stop="downloadImage(image)"
              />
            </div>
          </div>
        </div>

        <!-- 图片信息 -->
        <div class="image-info">
          <div class="image-name" :title="image.filename">
            {{ image.filename }}
          </div>
          <div class="image-meta">
            <span>{{ formatFileSize(image.size) }}</span>
            <span>{{ formatDate(image.last_modified) }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 图片列表视图 -->
    <div v-else class="image-list">
      <el-table :data="images" style="width: 100%" @row-click="previewImage">
        <el-table-column label="预览" width="100">
          <template slot-scope="scope">
            <img
              :src="scope.row.full_url || scope.row.url"
              :alt="scope.row.filename"
              class="list-thumbnail"
              @error="handleImageError"
            >
          </template>
        </el-table-column>

        <el-table-column label="文件名" prop="filename" min-width="200">
          <template slot-scope="scope">
            <span :title="scope.row.filename">{{ scope.row.filename }}</span>
          </template>
        </el-table-column>

        <el-table-column label="文件大小" width="100">
          <template slot-scope="scope">
            {{ formatFileSize(scope.row.size) }}
          </template>
        </el-table-column>

        <el-table-column label="创建时间" width="160">
          <template slot-scope="scope">
            {{ formatDate(scope.row.last_modified) }}
          </template>
        </el-table-column>

        <el-table-column label="操作" width="150">
          <template slot-scope="scope">
            <el-button
              type="text"
              size="small"
              icon="el-icon-view"
              @click.stop="previewImage(scope.row)"
            >
              预览
            </el-button>
            <el-button
              type="text"
              size="small"
              icon="el-icon-download"
              @click.stop="downloadImage(scope.row)"
            >
              下载
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div v-if="pagination.total > 0" class="pagination-container">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :current-page="pagination.current_page"
        :page-sizes="[12, 24, 48, 96]"
        :page-size="pageSize"
        :total="pagination.total"
        @size-change="handlePageSizeChange"
        @current-change="handlePageChange"
      />
    </div>

    <!-- 图片预览对话框 -->
    <el-dialog
      :visible.sync="previewDialog.visible"
      :title="previewDialog.image ? previewDialog.image.filename : '图片预览'"
      class="image-preview-dialog"
      width="80%"
      top="5vh"
      append-to-body
      :before-close="closePreview"
    >
      <div v-if="previewDialog.image" class="preview-content">
        <div class="preview-image-container">
          <img
            :src="previewDialog.image.full_url || previewDialog.image.url"
            :alt="previewDialog.image.filename"
            class="preview-image"
          >
        </div>

        <div class="preview-info">
          <el-row :gutter="20">
            <el-col :span="12">
              <div class="info-item">
                <strong>文件名：</strong>
                {{ previewDialog.image.filename }}
              </div>
              <div class="info-item">
                <strong>文件大小：</strong>
                {{ formatFileSize(previewDialog.image.size) }}
              </div>
            </el-col>
            <el-col :span="12">
              <div class="info-item">
                <strong>创建时间：</strong>
                {{ formatDate(previewDialog.image.last_modified) }}
              </div>
              <div class="info-item">
                <strong>访问链接：</strong>
                <el-input
                  :value="previewDialog.image.full_url"
                  readonly
                  size="mini"
                  class="url-input"
                >
                  <el-button
                    slot="append"
                    icon="el-icon-document-copy"
                    @click="copyUrl(previewDialog.image.full_url)"
                  />
                </el-input>
              </div>
            </el-col>
          </el-row>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="closePreview">关闭</el-button>
        <el-button
          type="primary"
          icon="el-icon-download"
          @click="downloadImage(previewDialog.image)"
        >
          下载图片
        </el-button>
      </div>
    </el-dialog>

    <!-- 统计信息对话框 -->
    <el-dialog
      :visible.sync="statsDialog.visible"
      title="AI图片统计信息"
      width="60%"
      @open="loadStats"
    >
      <div v-loading="statsDialog.loading">
        <div v-if="statsDialog.data">
          <el-row :gutter="20" style="margin-bottom: 20px;">
            <el-col :span="8">
              <el-card shadow="hover" class="stats-card">
                <div class="stats-number">{{ statsDialog.data.total_images }}</div>
                <div class="stats-label">总图片数量</div>
              </el-card>
            </el-col>
            <el-col :span="8">
              <el-card shadow="hover" class="stats-card">
                <div class="stats-number">{{ statsDialog.data.total_size_mb }}MB</div>
                <div class="stats-label">总存储大小</div>
              </el-card>
            </el-col>
            <el-col :span="8">
              <el-card shadow="hover" class="stats-card">
                <div class="stats-number">{{ Object.keys(statsDialog.data.projects).length }}</div>
                <div class="stats-label">涉及项目数</div>
              </el-card>
            </el-col>
          </el-row>

          <!-- 项目详情 -->
          <el-table
            :data="projectStatsArray"
            style="width: 100%"
            max-height="300"
          >
            <el-table-column label="项目ID" prop="project_id" width="100" />
            <el-table-column label="图片数量" prop="count" width="100" />
            <el-table-column label="存储大小" width="120">
              <template slot-scope="scope">
                {{ formatFileSize(scope.row.size) }}
              </template>
            </el-table-column>
            <el-table-column label="最新生成时间" width="160">
              <template slot-scope="scope">
                {{ scope.row.latest_date ? formatDate(scope.row.latest_date) : '-' }}
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="statsDialog.visible = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getAiGeneratedImages, deleteAllAiGeneratedImages, getAiImagesStats } from '@/api/cms/ai_generated_images'

export default {
  name: 'AiGeneratedImageGallery',
  data() {
    return {
      // 图片数据
      images: [],
      loading: false,

      // 分页数据
      pagination: {
        current_page: 1,
        per_page: 24,
        total: 0,
        total_pages: 0,
        has_more: false
      },
      pageSize: 24,

      // 视图设置
      viewMode: 'grid', // grid | list

      // 预览对话框
      previewDialog: {
        visible: false,
        image: null
      },

      // 统计对话框
      statsDialog: {
        visible: false,
        loading: false,
        data: null
      }
    }
  },

  computed: {
    // 是否为管理员
    isAdmin() {
      return this.$store.getters.roles?.includes('admin') ||
             this.$store.getters.roles?.includes('ai_model_manager')
    },

    // 项目统计数组（用于表格显示）
    projectStatsArray() {
      if (!this.statsDialog.data?.projects) return []

      return Object.entries(this.statsDialog.data.projects).map(([projectId, stats]) => ({
        project_id: projectId,
        count: stats.count,
        size: stats.size,
        latest_date: stats.latest_date
      }))
    }
  },

  mounted() {
    this.loadImages()
  },

  methods: {
    // 加载图片列表
    async loadImages() {
      this.loading = true

      try {
        const params = {
          page: this.pagination.current_page,
          limit: this.pageSize
        }

        const response = await getAiGeneratedImages(params)

        if (response.success) {
          this.images = response.data.images || []
          this.pagination = {
            current_page: response.data.pagination?.current_page || 1,
            per_page: response.data.pagination?.per_page || this.pageSize,
            total: response.data.pagination?.total || 0,
            total_pages: response.data.pagination?.total_pages || 0,
            has_more: response.data.pagination?.has_more || false
          }
        } else {
          this.$message.error(response.msg || '获取图片列表失败')
        }
      } catch (error) {
        console.error('加载图片列表错误:', error)
        this.$message.error('加载图片列表失败')
      } finally {
        this.loading = false
      }
    },

    // 刷新图片
    refreshImages() {
      this.pagination.current_page = 1
      this.loadImages()
    },

    // 处理分页变化
    handlePageChange(page) {
      this.pagination.current_page = page
      this.loadImages()
    },

    // 处理每页大小变化
    handlePageSizeChange(size) {
      this.pageSize = size
      this.pagination.current_page = 1
      this.loadImages()
    },

    // 预览图片
    previewImage(image) {
      this.previewDialog.image = image
      this.previewDialog.visible = true
    },

    // 关闭预览
    closePreview() {
      this.previewDialog.visible = false
      this.previewDialog.image = null
    },

    // 下载图片
    downloadImage(image) {
      const link = document.createElement('a')
      link.href = image.full_url || image.url
      link.download = image.filename
      link.target = '_blank'
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)

      this.$message.success('开始下载图片')
    },

    // 复制URL
    copyUrl(url) {
      if (navigator.clipboard) {
        navigator.clipboard.writeText(url).then(() => {
          this.$message.success('链接已复制到剪贴板')
        }).catch(() => {
          this.fallbackCopyTextToClipboard(url)
        })
      } else {
        this.fallbackCopyTextToClipboard(url)
      }
    },

    // 备用复制方法
    fallbackCopyTextToClipboard(text) {
      const textArea = document.createElement('textarea')
      textArea.value = text
      document.body.appendChild(textArea)
      textArea.focus()
      textArea.select()

      try {
        document.execCommand('copy')
        this.$message.success('链接已复制到剪贴板')
      } catch (err) {
        this.$message.error('复制失败，请手动复制')
      }

      document.body.removeChild(textArea)
    },

    // 处理图片加载错误
    handleImageError(event) {
      event.target.src = '/static/images/image-error.png' // 设置错误占位图
    },

    // 处理图片加载成功
    handleImageLoad(event) {
      event.target.classList.add('loaded')
    },

    // 显示统计对话框
    showStatsDialog() {
      this.statsDialog.visible = true
    },

    // 加载统计数据
    async loadStats() {
      this.statsDialog.loading = true

      try {
        const response = await getAiImagesStats()

        if (response.success) {
          this.statsDialog.data = response.data
        } else {
          this.$message.error(response.msg || '获取统计信息失败')
        }
      } catch (error) {
        console.error('加载统计信息错误:', error)
        this.$message.error('加载统计信息失败')
      } finally {
        this.statsDialog.loading = false
      }
    },

    // 确认删除所有图片
    confirmDeleteAll() {
      this.$confirm(
        '此操作将永久删除当前项目的所有AI生成图片，且无法恢复。是否继续？',
        '危险操作确认',
        {
          confirmButtonText: '确定删除',
          cancelButtonText: '取消',
          type: 'warning',
          dangerouslyUseHTMLString: true
        }
      ).then(() => {
        this.deleteAllImages()
      })
    },

    // 删除所有图片
    async deleteAllImages() {
      const loading = this.$loading({
        lock: true,
        text: '正在删除图片...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })

      try {
        const response = await deleteAllAiGeneratedImages()

        if (response.success) {
          this.$message.success(response.msg || '删除成功')
          this.refreshImages()
        } else {
          this.$message.error(response.msg || '删除失败')
        }
      } catch (error) {
        console.error('删除图片错误:', error)
        this.$message.error('删除失败')
      } finally {
        loading.close()
      }
    },

    // 格式化文件大小
    formatFileSize(bytes) {
      if (bytes === 0) return '0 B'

      const k = 1024
      const sizes = ['B', 'KB', 'MB', 'GB']
      const i = Math.floor(Math.log(bytes) / Math.log(k))

      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
    },

    // 格式化日期
    formatDate(dateString) {
      if (!dateString) return '-'

      const date = new Date(dateString)
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.ai-image-gallery {
  padding: 20px;

  .gallery-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding: 15px;
    background: #f8f9fa;
    border-radius: 6px;

    .header-left {
      display: flex;
      align-items: center;
      gap: 15px;

      .gallery-title {
        margin: 0;
        color: #303133;
        font-size: 18px;
        display: flex;
        align-items: center;
      }
    }

    .header-right {
      display: flex;
      align-items: center;
    }
  }

  .image-stats {
    margin-bottom: 20px;
  }

  .loading-container {
    text-align: center;
  }

  .empty-state {
    text-align: center;
    padding: 80px 0;

    .empty-content {
      color: #909399;
    }
  }

  .image-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
    gap: 20px;
    margin-bottom: 30px;

    .image-card {
      border: 1px solid #e4e7ed;
      border-radius: 8px;
      overflow: hidden;
      transition: all 0.3s ease;
      cursor: pointer;

      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
      }

      .image-wrapper {
        position: relative;
        height: 200px;
        overflow: hidden;
        background: #f5f7fa;

        .gallery-image {
          width: 100%;
          height: 100%;
          object-fit: cover;
          transition: opacity 0.3s ease;
          opacity: 0;

          &.loaded {
            opacity: 1;
          }
        }

        .image-overlay {
          position: absolute;
          top: 0;
          left: 0;
          right: 0;
          bottom: 0;
          background: rgba(0, 0, 0, 0.6);
          display: flex;
          align-items: center;
          justify-content: center;
          opacity: 0;
          transition: opacity 0.3s ease;

          .image-actions {
            display: flex;
            gap: 10px;
          }
        }

        &:hover .image-overlay {
          opacity: 1;
        }
      }

      .image-info {
        padding: 12px;

        .image-name {
          font-size: 14px;
          color: #303133;
          margin-bottom: 8px;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }

        .image-meta {
          display: flex;
          justify-content: space-between;
          font-size: 12px;
          color: #909399;
        }
      }
    }
  }

  .image-list {
    margin-bottom: 30px;

    .list-thumbnail {
      width: 60px;
      height: 60px;
      object-fit: cover;
      border-radius: 4px;
    }
  }

  .pagination-container {
    text-align: center;
    padding: 20px 0;
  }
}

// 预览对话框样式
::v-deep .image-preview-dialog {
  .el-dialog__body {
    padding: 20px;
  }

  .preview-content {
    .preview-image-container {
      text-align: center;
      margin-bottom: 20px;

      .preview-image {
        max-width: 100%;
        max-height: 60vh;
        object-fit: contain;
        border-radius: 8px;
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
      }
    }

    .preview-info {
      .info-item {
        margin-bottom: 12px;
        color: #606266;

        strong {
          color: #303133;
        }

        .url-input {
          margin-top: 5px;
        }
      }
    }
  }
}

// 统计卡片样式
.stats-card {
  text-align: center;
  padding: 20px;

  .stats-number {
    font-size: 28px;
    font-weight: bold;
    color: #1EB7E6;
    margin-bottom: 8px;
  }

  .stats-label {
    color: #606266;
    font-size: 14px;
  }
}
</style>
